import { pw } from "@/utils";
import { REQUEST_GET } from "..";

export async function request(options, config = {}) {
    const controller = new AbortController();
    const timeout = config.timeout ?? 0;
    let st;

    if (timeout > 0) {
        st = setTimeout(() => controller.abort(), timeout);
    }

    const [responseError, response] = await pw(fetch(options.url, {
        method : options.method,
        body   : options.method == REQUEST_GET ? undefined : options.data,
        headers: options.headers,
        signal : controller.signal
    }));

    clearTimeout(st);

    if (responseError) {
        if (process.env.NODE_ENV === 'development') {
            console.error('[API]', options.url, responseError.message);
        }

        return Promise.reject(responseError);
    }

    return response;
}

export async function requestJson(options, config = {}) {
    const [responseError, response] = await pw(request(options));

    if (responseError) {
        return Promise.reject(responseError);
    }

    const [jsonError, result] = await pw(response.json());

    if (jsonError) {
        return Promise.reject(jsonError);
    }

    options.onResponse?.('json', result);

    if (result.code !== 200 || !result.success) {
        let showMsg = '';

        if (result.code === -1) {
            showMsg = result.message + 'deleteFail';
        } else {
            showMsg = result.message;
        }

        const error = new Error(ajaxErrorMessage(showMsg));

        error.response = result;

        return Promise.reject(error);
    }

    return result;
}
